package com.hhq.demo.mvc;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author HHQ
 * @date 2021年12月10日
 */
public class DispatcherServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        String path = config.getInitParameter("contentConfig");
        InputStream is = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);
        HandlerMapping.load(is);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        HandlerMapping.MVCConfig mapping = HandlerMapping.get(uri);
        Method method = mapping.getMethod();
        Object obj = mapping.getObj();
        ResponseType type = mapping.getType();
        Object result = null;
        try {
            result = method.invoke(obj, req, resp);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        switch (type) {
            case TEXT:
                //如果放回方式为VIEW，则直接重定向
                resp.getWriter().write((String) result);
                break;
            case VIEW:
                //如果为TEXT则以文本形式返回
                resp.sendRedirect((String) result);
                break;
        }
    }
}
